package com.woniushop.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woniushop.entity.Goods;
import com.woniushop.entity.PageBean;
import com.woniushop.entity.User;
import com.woniushop.service.GoodsService;
import com.woniushop.service.imple.GoodsServiceImple;
import com.woniushop.utils.ControllerUtils;

/**
 * Servlet implementation class GoodsTypeServlet
 */
@WebServlet("/goods")
@MultipartConfig
public class GoodsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private GoodsService goodsService = new GoodsServiceImple();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		switch (opr) {
		case "list":// 分页查询所有商品
			list(request, response);
			break;
		case "add":// 增加商品
			add(request, response);
			break;
		case "initUpdate":// 初始化修改页面
			initUpdate(request, response);
			break;
		case "update":// 修改商品
			update(request, response);
			break;
		case "changeGstate":// 修改商品状态
			changeGstate(request, response);
			break;
		case "listByTerms":// 分页查询符合条件的商品
			listByTerms(request, response);
			break;
		case "search":// 搜索符合条件的商品
			search(request, response);
			break;
		case "initGoodsInfo":// 初始化商品详情页面
			initGoodsInfo(request, response);
			break;
		default:

			break;
		}
	}

	/**
	 * 初始化商品详情页面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void initGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 获得gid
			Integer gid = Integer.parseInt(request.getParameter("gid"));
			// 根据gid查找商品
			Goods goods = goodsService.findOne(gid);
			if (goods == null) {
				request.setAttribute("msg", "该商品不存在，请刷新后重试。");
			} else {
				// 将商品存入请求作用域
				request.setAttribute("goods", goods);
			}
		} catch (Exception e) {
			request.setAttribute("msg", "页面出错，请稍后再试！");
		}
		request.getRequestDispatcher("goodsInfo.jsp").forward(request, response);
	}

	private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获得搜索关键字
		String wd = request.getParameter("wd");
		wd = wd.trim();

		// 创建pageBean
		PageBean pageBean = new PageBean();

		// 获得页码，如果没有页码，则设置页码为1
		String page = request.getParameter("page");
		if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
			pageBean.setPage(1);
		} else {
			pageBean.setPage(Integer.parseInt(page));
		}

		// 设置分页大小
		pageBean.setPageSize(5);

		// 设置搜索条件
		Goods goods = new Goods();
		goods.setGdesc(wd);
		goods.setGname(wd);

		List<Goods> list = goodsService.findByPage(pageBean, goods);

		request.setAttribute("list", list);
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("wd", wd);

		request.getRequestDispatcher("search.jsp").forward(request, response);
	}

	/**
	 * 分页查询符合条件的商品
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void listByTerms(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String[]> parameterMap = request.getParameterMap();
			Goods goods = (Goods) ControllerUtils.mapToObject(parameterMap, Goods.class);
			if (goods.getGtid() != null && goods.getGtid() < 1) {
				goods.setGtid(null);
			}

			// 创建pageBean
			PageBean pageBean = new PageBean();

			// 获得页码，如果没有页码，则设置页码为1
			String page = request.getParameter("page");
			if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
				pageBean.setPage(1);
			} else {
				pageBean.setPage(Integer.parseInt(page));
			}

			// 设置分页大小
			Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
			pageBean.setPageSize(pageSize);

			// 获得所有数据
			List<Goods> list = goodsService.findByPage(pageBean, goods);
			map.put("list", list);
			map.put("pageBean", pageBean);
			map.put("gtid", goods.getGtid());
			map.put("msg", "ok");
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);

	}

	/**
	 * 修改商品状态
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	private void changeGstate(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() == 3) {
				map.put("msg", "null");
			} else {
				// 获得商品id
				Integer gid = Integer.parseInt(request.getParameter("gid"));
				// 获得商品目标状态
				Integer gstate = Integer.parseInt(request.getParameter("gstate"));
				// 修改商品状态
				goodsService.changeGstate(gid, gstate);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 修改商品
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() == 3) {
				request.setAttribute("msg", "null");
			} else {
				// 获得用户对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				Goods goods = (Goods) ControllerUtils.mapToObject(parameterMap, Goods.class);

				// 获得上传的文件
				Part part = request.getPart("gpic");
				// 获得原文件路径
				String gpic = goodsService.findOne(goods.getGid()).getGpic();
				goods.setGpic(gpic);

				String fileName = part.getSubmittedFileName();
				// 如果上传了新图片，则重写原图片文件
				if (fileName != null && fileName.length() > 0) {
					// 获得文件拓展名
					String suffix = fileName.substring(fileName.lastIndexOf('.'));

					// 得到tomcat的绝对路径,并创建存储商品图片的文件夹
					String path = getServletContext().getRealPath("/img/goods");

					// 产生一个唯一的文件名
					fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
					// 将文件写入
					part.write(path + "/" + fileName);
					// 将文件路径存入goods
					goods.setGpic("img/goods/" + fileName);

					// 将原文件删除
					File oldPic = new File(path + gpic.substring(gpic.lastIndexOf('/')));
					oldPic.delete();
				}

				// 设置修改人id
				goods.setUid(loginUser.getUid());

				// 设置商品状态为上架
				goods.setGstate(loginUser.getUid());
				goodsService.update(goods);
				request.setAttribute("msg", "ok");
			}
		} catch (Exception e) {
			request.setAttribute("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}
		request.getRequestDispatcher("manage/goodsUpdate.jsp").forward(request, response);
	}

	/**
	 * 初始化修改页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void initUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			// 获得gid
			Integer gid = Integer.parseInt(request.getParameter("gid"));
			// 根据gid查找商品
			Goods goods = goodsService.findOne(gid);
			if (goods == null) {
				request.setAttribute("msg", "该商品不存在，请刷新后重试。");
			} else {
				// 将商品存入请求作用域
				request.setAttribute("goods", goods);
			}
		} catch (Exception e) {
			request.setAttribute("msg", "页面出错，请稍后再试！");
		}
		request.getRequestDispatcher("manage/goodsUpdate.jsp").forward(request, response);
	}

	/**
	 * 增加商品
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() == 3) {
				request.setAttribute("msg", "null");
			} else {
				// 获得用户对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				Goods goods = (Goods) ControllerUtils.mapToObject(parameterMap, Goods.class);

				// 获得上传的文件
				Part part = request.getPart("gpic");
				// 获得文件拓展名
				String fileName = part.getSubmittedFileName();
				String suffix = fileName.substring(fileName.lastIndexOf('.'));

				// 得到tomcat的绝对路径,并创建存储商品图片的文件夹
				String path = getServletContext().getRealPath("/img/goods");
				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}

				// 产生一个唯一的文件名
				fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
				// 将文件写入
				part.write(path + "/" + fileName);

				// 将文件路径存入goods
				goods.setGpic("img/goods/" + fileName);

				// 设置创建人id
				goods.setUid(loginUser.getUid());

				// 设置商品状态为上架
				goods.setGstate(loginUser.getUid());
				goodsService.add(goods);
				request.setAttribute("msg", "ok");
			}
		} catch (Exception e) {
			request.setAttribute("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}
		request.getRequestDispatcher("manage/goodsAdd.jsp").forward(request, response);
	}

	/**
	 * 分页查询所有商品
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void list(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 创建pageBean
			PageBean pageBean = new PageBean();

			// 获得页码，如果没有页码，则设置页码为1
			String page = request.getParameter("page");
			if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
				pageBean.setPage(1);
			} else {
				pageBean.setPage(Integer.parseInt(page));
			}

			// 设置分页大小
			pageBean.setPageSize(3);

			// 获得分页数据
			List<Goods> list = goodsService.findByPage(pageBean, new Goods());
			map.put("list", list);
			map.put("pageBean", pageBean);
			map.put("msg", "ok");
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
